package com.project.restaurant.thirdpart.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.project.restaurant.common.api.ServiceReturn;
import com.project.restaurant.common.api.ServiceStateCode;
import com.project.restaurant.thirdpart.dto.LookPayResult;
import com.project.restaurant.thirdpart.dto.WXNativePayOrder;

import com.project.restaurant.thirdpart.enums.WXPayState;
import com.project.restaurant.thirdpart.service.WXNativePayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WXNativePayServiceImpl implements WXNativePayService{

    @Autowired
    WXPay wxPay;

    @Override
    public ServiceReturn<String> createNativePayUrl(WXNativePayOrder order) throws Exception {
        Map<String, String> reqData = new HashMap<>();
        reqData.put("body",order.getDescription());
        //订单号与该支付凭证绑定
        reqData.put("out_trade_no", String.valueOf(order.getOrderId()));
        //过期时间
        reqData.put("time_expire", order.getOrderExpirationTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        reqData.put("fee_type", "CNY");
        reqData.put("total_fee", String.valueOf(order.getPayAmount()));
        reqData.put("notify_url", order.getNotifyUrl());
        reqData.put("trade_type","NATIVE");
        reqData.put("product_id", String.valueOf(order.getProductId()));
        try {
            Map<String, String> resp = wxPay.unifiedOrder(reqData);
            log.info(resp.toString());
            if(ServiceStateCode.SUCCESS.name().equals(resp.get("result_code"))){
                return new ServiceReturn<>(ServiceStateCode.SUCCESS,resp.get("code_url"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception("支付请求异常");
    }

    @Override
    public ServiceReturn<LookPayResult> isPaySuccess(String orderId) throws Exception {
        Map<String, String> reqData = new HashMap<>();
        reqData.put("out_trade_no", orderId.replaceAll("-",""));
        Map<String, String> resp = wxPay.orderQuery(reqData);
        if(resp.get("return_msg").equals("OK")){
            LookPayResult payResult = new LookPayResult();
            //设置查看了哪个订单的支付状态
            payResult.setOrderId(orderId);
            //获取微信支付的状态
            WXPayState tradeState = WXPayState.valueOf(resp.get("trade_state"));
            payResult.setPayState(tradeState);
            //如果该微信支付的状态是支付成功，则响应数据里有transaction_id支付凭证
            if(WXPayState.SUCCESS.equals(tradeState)) {
                payResult.setTransactionId(resp.get("transaction_id"));
            }
            return new ServiceReturn<>(ServiceStateCode.SUCCESS,payResult);
        }
        throw new Exception("查询支付订单出错");
    }
}
